package cn.itcast.bos.web.action.common;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.springframework.data.domain.Page;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;



public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{
	
	//抽取模型
	protected T model;
	
	@Override
	public T getModel(){
		return model;
	}
	
	//构造完成创建模型对象
	public BaseAction(){
		// 构造子类Action对象 ，获取继承父类型的泛型
		// AreaAction extends BaseAction<Area>
		// BaseAction<Area>
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		// 获取类型第一个泛型参数
		ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
		Class<T> modelClass = (Class<T>) parameterizedType
				.getActualTypeArguments()[0];
		try {
			model = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型构造失败...");
		}
	}
	//条件分页查询优化
	//接收请求的数据
	protected Integer page;
	protected Integer rows;
	
	
	public void setPage(Integer page) {
		this.page = page;
	}


	public void setRows(Integer rows) {
		this.rows = rows;
	}
	//封装响应数据并压入值栈
	protected void pushPageDataToValueStack(Page<T> pageData) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		
		//把map压入值栈
		ActionContext.getContext().getValueStack().push(map);
	}
}
